<?php
/**
 * +----------------------------------------------------------------------
 * | 九月科技-ztuc.cn
 * +----------------------------------------------------------------------
 *                      .::::.
 *                    .::::::::.            | AUTHOR: siyu
 *                    :::::::::::           | EMAIL: ztucke@ztuc.cn
 *                 ..:::::::::::'           | DATETIME: 2020/01/31
 *             '::::::::::::'
 *                .::::::::::
 *           '::::::::::::::..
 *                ..::::::::::::.
 *              ``::::::::::::::::
 *               ::::``:::::::::'        .:::.
 *              ::::'   ':::::'       .::::::::.
 *            .::::'      ::::     .:::::::'::::.
 *           .:::'       :::::  .:::::::::' ':::::.
 *          .::'        :::::.:::::::::'      ':::::.
 *         .::'         ::::::::::::::'         ``::::.
 *     ...:::           ::::::::::::'              ``::.
 *   ```` ':.          ':::::::::'                  ::::..
 *                      '.:::::'                    ':'````..
 * +----------------------------------------------------------------------
 */
/**
 * Created by PhpStorm.
 * AuthGroup: Administrator
 * Date: 2020/3/14
 * Time: 17:18
 */

namespace app\lnadmin\controller;
use app\core\InitController;
use think\facade\View;
use app\lnadmin\model\admin\AuthGroup as AuthGroupModel;
use app\lnadmin\model\admin\AuthRule as AuthRuleModel;
use app\lnadmin\model\admin\AuthRule;

/**
 * 角色组
 * Class AuthGroup
 * @package app\controller\admin
 */
class AuthGroup extends InitController
{

    /**
     * 列表
     * @return string
     * @throws \Exception
     * @author: MK
     * @Time: 2020/4/8 20:07
     */
    public function list()
    {
        return View::fetch('authgroup');
    }

    /**
     * 部门管理JSON
     * @param string $limit 分页
     * @throws \think\db\exception\DbException
     */
    public function index_json($limit='15')
    {
        $list =  AuthGroupModel::paginate($limit);
        $this->result($list);
    }

    /**
     * 添加新的部门
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $param = $this->request->param();
            $verify = input('_verify', true);
            //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'authGroup');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $result = AuthGroupModel::create($param);
            if ($result == true) {
            add_admin_log('add', '角色菜单');// 记录行为日志
                $this->success('true','','添加成功', url('group/group'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        $authRule = collection(AuthRuleModel::where(['status' => 1])->order('weigh asc')->select())->toArray();
        foreach ($authRule as $k => $v) {
            //$authRule[$k]['open'] = true;
        }
        
        return View::fetch('addGroup', [
            'authRule' => list_to_tree($authRule)
        ]);
    }

    /**
     * 修改部门
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
          $verify = input('_verify', true);
            //验证规则
            if($verify!='0'){
                try{
                    $this->validate($param, 'authGroup');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            //更新数据
            $resule = AuthGroupModel::update($param);
           if ( $resule == true) {
            add_admin_log('edit', '角色菜单');// 记录行为日志
                $this->success('true','','修改成功', url('group/group'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data     = AuthGroupModel::where('id', input('id'))->find();
        $authRule = collection(AuthRuleModel::where(['status' => 1])->order('weigh asc')->field(['id','pid','url','name','icon as icons','weigh','status','ismenu'])->select())->toArray();
        foreach ($authRule as $k => $v) {
             //$authRule[$k]['open'] = true;
            $authRule[$k]['checked'] = in_array($v['id'], explode(',', $data['rules']));
        }
        return $this->fetch('saveGroup', [
            'data' => $data, 'authRule' => list_to_tree($authRule)
        ]);
    }

    /**
     * 删除部门
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            AuthGroupModel::destroy($param['id']);
            add_admin_log('del', '角色菜单');// 记录行为日志
            $this->success('删除成功');
        }
    }

    /**
     * 权限狗模式
     * @param $data
     * @param int $pid
     * @param int $lev
     * @return array
     * @author: MK
     * @Time: 2020/4/8 20:41
     */
    public function rules($data, $pid = 0, $lev = 0)
    {
        $tree = [];
        foreach ($data as $k => $v) {
            if ($v['pid'] == $pid) {
                $v['childlist'] = $this->rules($data, $v['id'], $lev + 1);
                unset($v['status']);    // 为什么这样写，因为匹配layui树组件
                unset($v['weigh']);
                unset($v['pid']);
                if (empty($v['childlist'])) {
                    unset($v['childlist']);
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }


    /**
     * 编辑树
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: MK
     * @Time: 2020/4/11 13:59
     */
    public function editTree()
    {
        $get = $this->request->get('rule');
        $rule = explode(',',$get);
        $data = $this->rule();
        foreach ($data as $k=>$v){
            $temp = [];
            foreach ($v['childlist'] as $k2=>$v2){

                if (in_array($v2['id'],$rule)){
                    $data[$k]['spread'] = true;
                    $v2['checked'] = true;
                    $temp[] = $v2;
                }else{
                    $temp[] = $v2;
                }
            }
            $data[$k]['childlist'] = $temp;
        }
        return $data;
    }
}